package priv.lhy.security.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: lihy
 * date: 2019/11/15 11:24
 * description:
 */
@RestController
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityController {

    @RequestMapping("/r/r1")
    public String r1(){
        return getUsername()+ " 访问 r1";
    }

    @RequestMapping("/r/r2")
    public String r2(){
        return getUsername()+ " 访问 r2";
    }

    @RequestMapping("/p/p1")
    public String p1(){
        return getUsername()+ " 访问 p1";
    }

    @PreAuthorize("hasAuthority('p2')")
    @RequestMapping("/p/p2")
    public String p2(){
        return getUsername()+ " 访问 p2";
    }

    @RequestMapping("/login‐success")
    public String loginSuccess(){
        return "login‐success";
    }

    /**
     * 获取当前登录用户名
     * @return
     */
    private String getUsername(){
        //当前登录用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(!authentication.isAuthenticated()){
            return null;
        }
        Object principal = authentication.getPrincipal();
        String username;
        if(principal instanceof UserDetails) {
            username = ((UserDetails)principal).getUsername();
        }else {
            username = principal.toString();
        }
        return username;
    }
}
